package cn.edu.upc.letao.service;

import cn.edu.upc.letao.dao.CommonMemberDao;
import cn.edu.upc.letao.model.SessionAdmin;
import cn.edu.upc.letao.model.SessionUser;
import org.hibernate.engine.spi.SessionOwner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Created by cheney on 2017/4/5.
 */
@Service
public class AuthService {
    @Autowired
    private CommonMemberDao commonMemberDao;
    @Autowired
    private HttpSession httpSession;

    //是否已经登录
    public boolean isAuthenticated(){
        System.out.println("in isAuthenticated user id:"+httpSession.getAttribute("visit_user_id"));
        if(httpSession.getAttribute("visit_user_id")==null){
            this.invalidLogin();
            return false;
        }else {//有id信息
            return true;
        }
    }

    //管理员是否已经登录
    public boolean adminIsAuthed(){
        if(httpSession.getAttribute("admin_visit_user_id")==null){
            this.invalidLogin();
            return false;
        }else {//有id信息
            return true;
        }
    }

    public SessionAdmin currentAdmin(){
        SessionAdmin SessionAdmin = null;
        //如果已经有
        if(httpSession.getAttribute("admin_visit_user_id")!=null){
            SessionAdmin = new SessionAdmin(
                    (long)httpSession.getAttribute("admin_visit_time"),
                    (String)httpSession.getAttribute("admin_visit_token"),
                    (String)httpSession.getAttribute("admin_visit_user_name"),
                    (int)httpSession.getAttribute("admin_visit_user_id")
            );//创建新session对象
        }
        return SessionAdmin;
    }

    public SessionUser currentUser(){
        SessionUser SessionUser = null;
        //如果已经有
        if(httpSession.getAttribute("visit_user_id")!=null){
            SessionUser = new SessionUser(
                    (long)httpSession.getAttribute("visit_time"),
                    (String)httpSession.getAttribute("visit_token"),
                    (String)httpSession.getAttribute("visit_user_name"),
                    (int)httpSession.getAttribute("visit_user_id")
            );//创建新session对象
        }
        return SessionUser;
    }

    public void invalidLogin(){
        httpSession.invalidate();
    }
}
